1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import { Drive_blob_path } from "@/lib/drive_server"
import { NextRequest, NextResponse } from "next/server"
import { createReadStream, statSync } from "fs"
import path from "path"
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ blobId: string }> }
) {
try {
const { blobId } = await params
const { searchParams } = new URL(request.url)
const filename = searchParams.get('filename') || 'download'
// Get the filesystem path for this blob
const blobPath = await Drive_blob_path(blobId)
// Get file stats
const stats = statSync(blobPath)
const fileSize = stats.size
// Determine content type based on file extension
const ext = path.extname(filename).toLowerCase()
const contentType = getContentType(ext)
// Create readable stream
const stream = createReadStream(blobPath)
// Convert stream to web stream
const readableStream = new ReadableStream({
start(controller) {
stream.on('data', (chunk: Buffer | string) => {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
controller.enqueue(new Uint8Array(buffer))
})
stream.on('end', () => {
controller.close()
})
stream.on('error', (error) => {
controller.error(error)
})
}
})
return new NextResponse(readableStream, {
headers: {
'Content-Type': contentType,
'Content-Length': fileSize.toString(),
'Content-Disposition': `attachment; filename="${filename}"`,
'Cache-Control': 'public, max-age=31536000', // Cache for 1 year
},
})
} catch (error) {
console.error('Error serving blob:', error)
return new NextResponse('File not found', { status: 404 })
}
}
function getContentType(extension: string): string {
const mimeTypes: Record<string, string> = {
'.pdf': 'application/pdf',
'.txt': 'text/plain',
'.md': 'text/markdown',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.doc': 'application/msword',
'.zip': 'application/zip',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.html': 'text/html',
'.htm': 'text/html',
}
return mimeTypes[extension] || 'application/octet-stream'
}
|